package com.itic.mall.mobile.users.openstore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.UserType;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.market.marketopenstore.persistence.model.MarketOpenstore;
import com.itic.mall.system.market.marketopenstore.persistence.model.MarketOpenstoreExample;
import com.itic.mall.system.market.marketopenstore.persistence.model.MarketOpenstoreExample.Criteria;
import com.itic.mall.system.market.marketopenstore.service.MarketOpenstoreService;
import com.itic.mall.system.market.openstoreword.persistence.model.OpenstoreWord;
import com.itic.mall.system.market.openstoreword.persistence.model.OpenstoreWordExample;
import com.itic.mall.system.market.openstoreword.persistence.vo.OpenstoreWordVo;
import com.itic.mall.system.market.openstoreword.service.OpenstoreWordService;
import com.itic.mall.system.users.openstore.persistence.model.OpenStore;
import com.itic.mall.system.users.openstore.service.OpenStoreService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample;

/**
 * 用户开店
 * @author 
 * @time 2017-12-4
 */

@Controller
@RequestMapping(value="/mobile/users/openstore")
public class UserOpenStoreInterface extends BaseMobileInterface{
	
	@Autowired
	private MarketOpenstoreService marketOpenstoreService;
	@Autowired
	private OpenstoreWordService openstoreWordService;
	@Autowired
	private OpenStoreService openStoreService;
	// 返回属性黑名单
    //private static String[] ignoreProperties = new String[] { "createTime","createUser", "isEffective", "updateTime", "orgCode","id","reorder","note","payNo","orderNo","userId" };
    
	
	public List<OpenstoreWordVo> getDefaultWords(){
		List<OpenstoreWordVo> result = new ArrayList<OpenstoreWordVo>();
		OpenstoreWordVo vo1 = new OpenstoreWordVo();
		vo1.setTitle("0元开店，无押金");
		vo1.setContent("入驻友惠家，无需收取任何费用，只要提交申请通过后即可开店");
		result.add(vo1);
		
		
		OpenstoreWordVo vo3 = new OpenstoreWordVo();
		vo3.setTitle("0基础，指导开店");
		vo3.setContent("定期店主培训，互相沟通学习如何开店，互相分享开店经验，日赚1000+");
		result.add(vo3);
		
		OpenstoreWordVo vo2 = new OpenstoreWordVo();
		vo2.setTitle("简单流程，服务方便");
		vo2.setContent("入驻简单快速，不收取任何佣金和服务费");
		result.add(vo2);
		
		return result;
	}
	
	/**
	 * 用户进入开店
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/index")
	@ResponseBody
	public Map<String,Object> index( HttpServletRequest request,HttpServletResponse response ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	Map<String, Object> dataMap = new HashMap<String,Object>();
	    	dataMap.put("banner", "http://file.jhjvip.cn/images/openstore.png");
	    	dataMap.put("list", getDefaultWords());
	    	MarketOpenstoreExample example = new MarketOpenstoreExample();
	    	Criteria criteria = example.createCriteria();
	    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	    	List<MarketOpenstore> list = marketOpenstoreService.list(example);
	    	if( list.size() > 0 ){
	    		MarketOpenstore openstore = list.get(0);
	    		dataMap.put("banner", openstore.getBanner());
	    		OpenstoreWordExample example2 = new OpenstoreWordExample();
	    		com.itic.mall.system.market.openstoreword.persistence.model.OpenstoreWordExample.Criteria criteria2 = example2.createCriteria();
	    		criteria2.andIsEffectiveEqualTo(DBConst.TRUE);
	    		criteria2.andBannerIdEqualTo(openstore.getId());
	    		List<OpenstoreWord> list2 = openstoreWordService.list(example2);
	    		dataMap.put("list", ValueHelper.tranList2MapList(list2, new String[] { "createTime","createUser", "isEffective", "updateTime", "orgCode","id","reorder","note","bannerId" }));
	    	}
	    	resultMap.put(DATA, dataMap);
	    	errorCode = SUCCESS_ERROR_CODE;
	       	errorMsg = SUCCESS_ERROR_MSG;
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"APP用户进入开店",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	/**
	 * 用户进入开店
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/isOpenIos")
	@ResponseBody
	public Map<String,Object> isOpenIos( HttpServletRequest request,HttpServletResponse response, String token, String appId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
	    		UsersMall user = getUsersByTokenAndAppId(token,appId);
	    		if( null != user ){
	    			Map<String, Object> dataMap = new HashMap<String,Object>();
	    			Integer status = -1;
	    			//判断用户是否入驻
	    			String type = user.getType();
	    			if( UserType.ydz.getType().equals(type) ){
	    				//dataMap.put("status", 2);//您nn云店主了
	    				status = 2;
	    			}else{
	    				//是否提交过申请记录，且未审核状态
	    				List<OpenStore>  list = openStoreService.getByUserIdAndStatus(user.getId(),"0");
	    				if( list.size()>0 ){
	    					//dataMap.put("status", 1);//您nn云店主了
	    					status = 1;
	    				}
	    			}
	    			dataMap.put("status", status);
	    			dataMap.put("phone", user.getUserPhone());//您nn云店主了
	    			
	    			resultMap.put(DATA, dataMap);
	    			errorCode = SUCCESS_ERROR_CODE;
			       	errorMsg = SUCCESS_ERROR_MSG;
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"APP用户进入开店",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	/**
	 * 用户进入开店
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/isOpen")
	@ResponseBody
	public Map<String,Object> isOpen( HttpServletRequest request,HttpServletResponse response, String token, String appId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
	    		UsersMall user = getUsersByTokenAndAppId(token,appId);
	    		if( null != user ){
	    			//判断用户是否入驻
	    			String type = user.getType();
	    			if( "002".equals(type) ){
	    				errorCode = YUNED_ERROR_CODE;
				       	errorMsg = YUNED_ERROR_MSG;
	    			}else{
	    				//是否提交过申请记录，且未审核状态
	    				List<OpenStore>  list = openStoreService.getByUserIdAndStatus(user.getId(),"0");
	    				if( list.size()>0 ){
	    					errorCode = TIJIANED_ERROR_CODE;
	    			       	errorMsg = TIJIANED_ERROR_MSG;//已提交审核
	    				}else{
	    					resultMap.put(DATA, user.getUserPhone());
	    					errorCode = SUCCESS_ERROR_CODE;
	    			       	errorMsg = SUCCESS_ERROR_MSG;
	    				}
	    			}
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"APP用户进入开店",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	
	/**
	 * 用户申请开店
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/ruzhu")
	@ResponseBody
	public Map<String,Object> ruzhu( HttpServletRequest request,HttpServletResponse response, String token, String appId, String phone, String weixinAccount, String inviteCode ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(weixinAccount) ){
	    		UsersMall user = getUsersByTokenAndAppId(token,appId);
	    		if( null != user ){
	    			if( UserType.user.getType().equals(user.getType()) ){

	    				List<OpenStore>  list = openStoreService.getByUserIdAndStatus(user.getId(),"0");
	    				if(list.isEmpty()) {
	    					//有邀请码的开店模式
				    		if( StringHelper.isNotBlank(inviteCode) ){
				    			UsersMall byInviteCodeUser = getUsersByInviteCode(inviteCode);
				    			//判断邀请码是否有效
					    		if( null != byInviteCodeUser ){
					    			/*//成功注册为云店主
					    			user.setType("002");
					    			user.setYunId(byInviteCodeUser.getId());
					    			user.setParentId(byInviteCodeUser.getId());
					    			//添加入驻申请表记录
					    			OpenStore openStore = new OpenStore();
					    			openStore.setPhone(phone);
					    			openStore.setWeixinAccount(weixinAccount);
					    			openStore.setStatus("0");
					    			openStore.setUserId(user.getId());
					    			usersMallService.ruzhuByCode(user,openStore);
					    			//开店成功添加StoreInfo信息 以及添加团队人数    			
					    			this.usersMallService.addTeamCountByUsersMall(user);
					    			errorCode = SUCCESS_ERROR_CODE;
							       	errorMsg = SUCCESS_ERROR_MSG;*/
					    			 //添加入驻申请表记录
					    			OpenStore openStore = new OpenStore();
					    			openStore.setPhone(phone);
					    			openStore.setWeixinAccount(weixinAccount);
					    			openStore.setStatus("0");
					    			openStore.setInviteCode(inviteCode);
					    			openStore.setUserId(user.getId());
					    			openStoreService.add(openStore);
					    			errorCode = SUCCESS_ERROR_CODE;
							       	errorMsg = SUCCESS_ERROR_MSG;
					    		}else{
					    			errorCode = INVITE_CODE_ERROR_CODE;
							       	errorMsg = INVITE_CODE_ERROR_MSG;
					    		}
				    		}else{
		    					//添加入驻申请表记录
				    			OpenStore openStore = new OpenStore();
				    			openStore.setPhone(phone);
				    			openStore.setWeixinAccount(weixinAccount);
				    			openStore.setStatus("0");
				    			openStore.setUserId(user.getId());
				    			openStoreService.add(openStore);
				    			errorCode = SUCCESS_ERROR_CODE;
				    			errorMsg = SUCCESS_ERROR_MSG;
				    		}
	    				}else {
	    					errorCode = TIJIANED_ERROR_CODE;
	    			       	errorMsg = TIJIANED_ERROR_MSG;//已提交审核
	    				}
	    			}else{
	    				errorCode = YUNED_ERROR_CODE;
				       	errorMsg = YUNED_ERROR_MSG;
	    			}
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"用户申请开店",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	/**
	 * 用户申请开店
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/ruzhuIos")
	@ResponseBody
	public Map<String,Object> ruzhuIos( HttpServletRequest request,HttpServletResponse response, String token, String appId, String phone, String weixinAccount, String inviteCode ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(weixinAccount) ){
	    		UsersMall user = getUsersByTokenAndAppId(token,appId);
	    		if( null != user ){
	    			if( UserType.user.getType().equals(user.getType()) ){
	    				//有邀请码的开店模式
			    		if( StringHelper.isNotBlank(inviteCode) ){
			    			UsersMall byInviteCodeUser = getUsersByInviteCode(inviteCode);
			    			//判断邀请码是否有效
				    		if( null != byInviteCodeUser ){
				    			/*//成功注册为云店主
				    			user.setType( UserType.ydz.getType() );
				    			user.setYunId(byInviteCodeUser.getId());
				    			user.setParentId(byInviteCodeUser.getId());
				    			//添加入驻申请表记录
				    			OpenStore openStore = new OpenStore();
				    			openStore.setPhone(phone);
				    			openStore.setWeixinAccount(weixinAccount);
				    			openStore.setStatus( "0" );
				    			openStore.setUserId(user.getId());
				    		
				    			usersMallService.ruzhuByCode(user,openStore);
				    			resultMap.put(DATA, 2);
				    			errorCode = SUCCESS_ERROR_CODE;
						       	errorMsg = SUCCESS_ERROR_MSG;*/
						       	
						        //添加入驻申请表记录
				    			OpenStore openStore = new OpenStore();
				    			openStore.setPhone(phone);
				    			openStore.setWeixinAccount(weixinAccount);
				    			openStore.setStatus("0");
				    			openStore.setInviteCode(inviteCode);
				    			openStore.setUserId(user.getId());
				    			openStoreService.add(openStore);
				    			
				    			resultMap.put(DATA, 1);
				    			errorCode = SUCCESS_ERROR_CODE;
						       	errorMsg = SUCCESS_ERROR_MSG;
				    		}else{
				    			//errorCode = INVITE_CODE_ERROR_CODE;
						       	//errorMsg = INVITE_CODE_ERROR_MSG;
						       	resultMap.put(DATA, 3);
				    			errorCode = SUCCESS_ERROR_CODE;
						       	errorMsg = SUCCESS_ERROR_MSG;
				    		}
			    		}else{
			    			//没有邀请码的入驻店主
			    			//是否提交过申请记录，且未审核状态
		    				List<OpenStore>  list = openStoreService.getByUserIdAndStatus(user.getId(),"0");
		    				if( list.size()>0 ){
		    					resultMap.put(DATA, 1);
				    			errorCode = SUCCESS_ERROR_CODE;
						       	errorMsg = SUCCESS_ERROR_MSG;
		    				}else{
		    					//添加入驻申请表记录
				    			OpenStore openStore = new OpenStore();
				    			openStore.setPhone(phone);
				    			openStore.setWeixinAccount(weixinAccount);
				    			openStore.setStatus("0");
				    			openStore.setUserId(user.getId());
				    			openStoreService.add(openStore);
				    			
				    			resultMap.put(DATA, 1);
				    			errorCode = SUCCESS_ERROR_CODE;
						       	errorMsg = SUCCESS_ERROR_MSG;
		    				}
			    		}
	    			}else{
	    				resultMap.put(DATA, 2);
		    			errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
	    			}
	    			
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"用户申请开店",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}

	/**
	 * 判断邀请码是否有用
	 * @param inviteCode
	 * @return
	 */
	private UsersMall getUsersByInviteCode(String inviteCode) {
		UsersMall user = null;
		if( StringHelper.isNotBlank(inviteCode) ){
			UsersMallExample example = new UsersMallExample();
			com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria criteria = example.createCriteria();
			criteria.andInvitingCodeEqualTo(inviteCode);
			List<UsersMall> list = usersMallService.list(example);
			if( list.size()>0 ){
				user = list.get(0);
			}
		}
		return user;
	}
}
